//获取应用实例
const app = getApp();
const util = require('../../utils/util.js');
const {
	$Toast
} = require('../../dist/base/index');
var pageNo = 1;
Page({
	data: {
		current: -1, //当前所在滑块的 index
		scrollLeft: 0, //滚动条的位置,一个选项卡宽度是90（自定义来自css），按比例90*n设置位置
		navlist: ["全部", "NodeJS", "Nginx", "前端", "数据库"],
		content: [],
		tip: "",
		loading: false,
		userInfo: {},
		user_comment: ''
	},
	//tab切换
	tab: function (event) {
		//通过cateUrl去查询自己发表的cateUrl类型的数据
		var cateUrl = this.data.navlist[event.target.dataset.current].labels;
		var that = this;
		this.setData({
			current: event.target.dataset.current
		});
		
		wx.request({
			url: util.basePath + '/article/v1/getLabelsArticle',
			method: "post",
			data: {
				cateUrl: cateUrl,
				openid: that.data.userInfo.openid,
				app_sid: that.data.userInfo.app_sid
			},
			header: {
				'content-type': 'application/json'
			},
			success(res) {
				if (res.data.status == 200) {
					that.setData({content: res.data.payload});
				} else {
					$Toast({
						content: res.data.err,
						type: 'error'
					});
					that.setData({ content: [] });
				}
			}
		});
	},
	onLoad: function (options) {
		var that = this;

		var userInfo = wx.getStorageSync("loginInfo");
		if(!userInfo) {
			wx.reLaunch({
				url: '/pages/userinfo/userinfo',
			});
		}
		that.setData({ userInfo: userInfo });

		that.getUserDesignArticle();
	},
	onPullDownRefresh: function () {
		// 显示顶部刷新图标
		wx.showNavigationBarLoading();
		this.data.content = [];
		pageNo = 1;
    this.getUserDesignArticle();

		setTimeout(function () {
			// 隐藏导航栏加载框
			wx.hideNavigationBarLoading();
			//停止当前页面下拉刷新。
			wx.stopPullDownRefresh()
		}, 1500)
	},
	onReachBottom: function () {
		var that = this;
		++pageNo;
		this.getUserDesignArticle();

	},

	modifyArticle: function(e) {
		var index = e.currentTarget.dataset.index;
		var that = this;

		wx.showActionSheet({
			itemList: ['修改', '删除'],
			success: function (res) {
				//修改文章
				if (res.tapIndex == 0) {
					wx.request({
						url: util.basePath + '/article/v1/articleDetail/' + index,
						method: "post",
						data: {

						},
						header: {
							'content-type': 'application/json'
						},
						success(res) {
							if (res.data.status == 200) {
								that.alterArticle(res.data.payload);
							} else {
								$Toast({
									content: res.data.err,
									type: 'error'
								});
							}
						}
					});
				} else {
					wx.request({
						url: util.basePath + '/article/v1/deleteArticle/' + index,
						method: "post",
						data: {
							
						},
						header: {
							'content-type': 'application/json'
						},
						success(res) {
							if (res.data.status == 200) {
								$Toast({
									content: '删除文章成功!',
									type: 'warn'
								});

								that.getUserDesignArticle();
							} else {
								$Toast({
									content: res.data.err,
									type: 'error'
								});
							}
						}
					});
				}
			}
		});
	},

	alterArticle: function (article) {
		var temp_content = [];
		var article_img = [];
		var article_content = [];
		//需要将markdown格式的文章内容转译成分段式的文章内容，首先需要取到外层的div标签
		article.content = article.content.split('<div class="markdown-text">')[1].split('</div>')[0];

		//然后按照<p>进行切割字符串去掉左边的<p>标签
		article.content = article.content.split('<p>');
		article.content.shift();

		//通过截取字符串截取掉每一段文字右边的</p>标签
		article.content.forEach(content => {
			temp_content.push(content.split('</p>')[0]);
		});

		//写作界面采用一段文字 + 一张图片格式，所以判断article_content[i]如果不是<img>标签，则对应文字的图片传入默认图片
		for(var i=0; i<temp_content.length; i++) {
			//不是数组最后一条数据，则需要将第i条数据与第i+1条数据一起判断
			if(i < temp_content.length - 1) {
				//temp_content[i]是文字，并且temp_content[i+1]是图片，则分别将temp_content[i]和temp_content[i+1]放入文字数组和图片数组
				if (temp_content[i].indexOf('<img') != 0 && temp_content[i + 1].indexOf('<img') == 0) {
					article_content.push(temp_content[i]);

					//照片是img标签的形式，需要截取字符串取到图片的url
					article_img.push(temp_content[i + 1].substr(10).split('">')[0]);
				}

				//如果temp_content[i]是文字，并且temp_content[i+1]也是文字，则将temp_content[i]放入文字数组，图片数组放入默认图片
				if (temp_content[i].indexOf('<img') != 0 && temp_content[i + 1].indexOf('<img') != 0) {
					article_content.push(temp_content[i]);
					article_img.push('/images/plus.png');
				}
			} else {
				//数组最后一条数据如果为图片就直接跳过，如果是文字则放入article_content，同时插入一个默认照片到article_img
				if (temp_content[i].indexOf('<img') != 0) {
					article_content.push(temp_content[i]);
					article_img.push('/images/plus.png');
				}
			}
		}

		wx.setStorage({
			key: 'alterArticle',
			data: {
				id: article.id,
				title: article.title,
				author: article.author,
				labels: article.labels,
				article_img: article_img,
				article_content: article_content
			},
		});

		wx.navigateTo({
			url: '/pages/writearticle/writearticle',
		});
	},

	onShareAppMessage: function (res) {
		return {
			title: '个人主页',
			path: '/pages/logs/logs'
		}
	},
	details(e) {
		//详情页跳转
		wx.navigateTo({
			url: '../details/details?id=' + e.currentTarget.id
		})
	},
	getUserDesignArticle: function () {
		var that = this;
		that.setData({
			loading: true,
			tip: "正在加载"
		});

		wx.request({
			url: util.basePath + '/article/v1/getUserArticleAndCategories',
			method: "post",
			data: {
				app_sid: that.data.userInfo.app_sid,
				openid: that.data.userInfo.openid
			},
			dataType: 'json',
			header: {
				'content-type': 'application/json'
			},
			success(res) {
				if (res.data.status == 200) {
					that.setData({
						loading: false,
						tip: "没有数据了",
						content: res.data.payload.data,
						navlist: res.data.payload.labels
					});
				} else {
					setTimeout(function () {
						that.setData({
							loading: false,
							tip: "没有数据了"
						})
					}, 1000);
				}
			}
		});
	}
});